//
//  WriteMedicalViewController.m
//  HandheldHospital
//
//  Created by zhangchao on 16/3/7.
//  Copyright © 2016年 zhangchao. All rights reserved.
//

#import "WriteMedicalViewController.h"
#import <Masonry.h>
#import "DataManager.h"
#import "PatientData.h"
#import "AddManagerViewController.h"
#import "Medical.h"


#define kWidth self.view.frame.size.width
#define kHeight self.view.frame.size.height
#define kShared [DataManager defaultManager]

@interface WriteMedicalViewController ()<UIPickerViewDataSource,UIPickerViewDelegate,UITextFieldDelegate>
/**
 *  详情按钮
 */
@property (nonatomic,strong) UIButton *detailed;
/**
 *  就诊人资料
 */
@property (nonatomic,strong) UITextField *manager;
/**
 *  就诊人
 */
@property (nonatomic,strong) PatientData *patient;
/**
 *  主诉
 */
@property (nonatomic,strong) UITextView *chiefComplaintTV;
/**
 *  现病史
 */
@property (nonatomic,strong) UITextView *presentHistoryTV;

@property (nonatomic,strong) UIPickerView *managerPV;
@end

@implementation WriteMedicalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"写病历";
    [self addViews];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(saveBtn)];
}

//页面布局
- (void)addViews
{
    self.detailed = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.detailed setTitle:@"详细" forState:UIControlStateNormal];
    [self.detailed setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.view addSubview:self.detailed];
    [self.detailed addTarget:self action:@selector(didClickDetailed) forControlEvents:UIControlEventTouchUpInside];
    [self.detailed mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.15);
        make.left.equalTo(self.view).offset(kWidth * 0.05);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.2, 40));
    }];
    
    self.manager = [[UITextField alloc] init];
    [self.view addSubview:self.manager];
    self.manager.layer.borderWidth = 0.5;
    self.manager.layer.cornerRadius = 5;
    self.manager.placeholder = @"请选择患者";
    self.manager.delegate = self;
    [self.manager mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.15);
        make.left.equalTo(self.view).offset(kWidth * 0.25);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.7, 40));
    }];
    
    self.managerPV = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 200)];
    self.managerPV.backgroundColor = [UIColor whiteColor];
    self.managerPV.delegate = self;
    self.managerPV.dataSource = self;
    self.manager.inputView = self.managerPV;
    
    UILabel *label1 = [[UILabel alloc] init];
    label1.text = @"主诉";
    label1.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:label1];
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.23);
        make.left.equalTo(self.view).offset(kWidth * 0.05);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.2, 40));
    }];
    
    self.chiefComplaintTV = [[UITextView alloc] init];
    self.chiefComplaintTV.layer.cornerRadius = 5;
    self.chiefComplaintTV.layer.borderWidth = 0.5;
    self.chiefComplaintTV.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:self.chiefComplaintTV];
    [self.chiefComplaintTV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.23);
        make.left.equalTo(self.view).offset(kWidth * 0.25);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.7, kHeight * 0.2));
    }];
    
    UILabel *label2 = [[UILabel alloc] init];
    label2.text = @"现病史";
    label2.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:label2];
    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.45);
        make.left.equalTo(self.view).offset(kWidth * 0.05);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.2, 40));
    }];
    
    self.presentHistoryTV = [[UITextView alloc] init];
    self.presentHistoryTV.layer.cornerRadius = 5;
    self.presentHistoryTV.layer.borderWidth = 0.5;
    self.presentHistoryTV.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:self.presentHistoryTV];
    [self.presentHistoryTV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kHeight * 0.45);
        make.left.equalTo(self.view).offset(kWidth * 0.25);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.7, kHeight * 0.2));
    }];
}

//保存按钮点击事件
- (void)saveBtn
{
    if(self.manager.text.length == 0)
    {
        [self showLabelWithString:@"请选择就诊人" AndBlock:nil];
    }
    else if(self.chiefComplaintTV.text.length == 0)
    {
        [self showLabelWithString:@"请写完病历再保存" AndBlock:nil];
    }
    else if(self.presentHistoryTV.text.length == 0)
    {
        [self showLabelWithString:@"请写完病历再保存" AndBlock:nil];
    }
    else
    {
        //取出医生信息
        AVQuery *query = [AVQuery queryWithClassName:@"SeekModel"];
        [query whereKey:@"currentUser" equalTo:[AVUser currentUser]];
        [query includeKey:@"currentUser"];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            //将信息赋给medical以便保存到数据库上
            Medical *medical = [Medical object];
            medical.patient = self.patient;
            medical.chiefComplaint = self.chiefComplaintTV.text;
            medical.presentHistory = self.presentHistoryTV.text;
            medical.writeTime = [NSString stringWithFormat:@"%@",[NSDate date]];
            medical.hospitalName = [objects firstObject][@"yiyuan"];
            medical.doctorName = [objects firstObject][@"name"];
            [self showAlertTwoButtonWithTitle:@"提示" AndMessage:@"是否确定，一旦保存不可修改" AndAlertStyle:UIAlertControllerStyleAlert AndOneButtonTitle:@"确定" AndTwoButtonTitle:@"取消" AndOneBlock:^{
                [medical saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    if(succeeded)//保存成功
                    {
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                    else //保存失败
                    {
                        [self showAlertOneButtonWithTitle:@"错误" AndMessage:@"未知错误导致保存失败"  AndAlertStyle:UIAlertControllerStyleAlert AndOneButtonTitle:@"确定" AndBlock:^{
                            [self.navigationController popViewControllerAnimated:YES];
                        }];
                    }
                }];
            } AndTwoBlock:nil];
        }];

    }
}

//textField的代理，判断有没有就诊人，如果有才可以写病历
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if(!(self.dataArray.count > 0))
    {
        [self showAlertOneButtonWithTitle:@"提示" AndMessage:@"没有可写的病历" AndAlertStyle:UIAlertControllerStyleAlert AndOneButtonTitle:@"确定" AndBlock:^{
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }
}

//点击详细按钮的事件
- (void)didClickDetailed
{
    //跳转到就诊人详情页
    AddManagerViewController *addManagerVC = [[AddManagerViewController alloc] init];
    addManagerVC.patient = self.patient;
    [self.navigationController pushViewController:addManagerVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//触摸view关闭键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.manager resignFirstResponder];
    [self.chiefComplaintTV resignFirstResponder];
    [self.presentHistoryTV resignFirstResponder];
    
}

#pragma mark pickerView的代理
//设置滚轮的个数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

//设置滚轮的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return self.dataArray.count;
}

//滚轮显示的内容
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    PatientData *patient = self.dataArray[row];
    self.manager.text = patient.name;
    self.patient = patient;
    return patient.name;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    PatientData *patient = self.dataArray[row];
    self.manager.text = patient.name;
    self.patient = patient;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
